package com.androidemu;

import java.nio.Buffer;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.Rect;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.view.SurfaceHolder;

public class EmuMedia {

	private static Bitmap bitmap;
	private static Rect dirty = new Rect();
	private static SurfaceHolder holder;
	private static Picture overlay;
	private static Rect region = new Rect();
	private static AudioTrack track;

	static void destroy() {
		overlay = null;
		if (bitmap != null) {
			bitmap.recycle();
			bitmap = null;
		}
		if (track!=null) {
			track.stop();
			track = null;
		}
	}
	
	static void setOverlay(Picture pic) {
		overlay = pic;
	}

	static void setSurface(SurfaceHolder h) {
		holder = h;
	}

	static Bitmap setSurfaceRegion(int x, int y, int w, int h) {
		region.set(x, y, x + w, y + h);
		if (bitmap!=null){
			if(bitmap.getWidth()==w&&bitmap.getHeight()==h) {
				return bitmap;
			} 
		}
		if (bitmap!=null) {
			bitmap.recycle();
		}
		bitmap = Bitmap.createBitmap(w, h, Config.RGB_565);
		return bitmap;
	}

	static void bitBlt(Buffer src, boolean flip) {
		if (src!=null) {
			bitmap.copyPixelsFromBuffer(src);
		}
		
		dirty.set(region);
		// Fill background
		Canvas canvas = holder.lockCanvas(dirty);
		if (flip)
			canvas.rotate(180, canvas.getWidth() / 2, canvas.getHeight() / 2);

		canvas.drawBitmap(bitmap, region.left, region.top,null);
		if (overlay!=null) {
			overlay.draw(canvas);
		}
		
		holder.unlockCanvasAndPost(canvas);
	}

	static void audioCreate(int rate, int bits, int channels) {
		int format = (bits == 16 ?
				AudioFormat.ENCODING_PCM_16BIT :
				AudioFormat.ENCODING_PCM_8BIT);
		int channelConfig = (channels == 2 ?
				AudioFormat.CHANNEL_CONFIGURATION_STEREO :
				AudioFormat.CHANNEL_CONFIGURATION_MONO);

		// avoid recreation if no parameters change
		if (track != null &&
				track.getSampleRate() == rate &&
				track.getAudioFormat() == format &&
				track.getChannelCount() == channels)
			return;
		try {
			int bufferSize = AudioTrack.getMinBufferSize(
					rate, channelConfig, format);
		
			track = new AudioTrack(
					AudioManager.STREAM_MUSIC,
					rate,
					channelConfig,
					format,
					bufferSize,
					AudioTrack.MODE_STREAM);

			if (track.getState() == AudioTrack.STATE_UNINITIALIZED)
				track = null;

		} catch (IllegalArgumentException e) {
			track = null;
		}
	}

	static void audioDestroy() {
		if (track != null) {
			track.stop();
			track = null;
		}
	}

	static void audioStart() {
		if (track != null)
			track.play();
	}

	static void audioStop() {
		if (track != null) {
			track.stop();
			track.flush();
		}
	}

	static void audioPause() {
		if (track != null)
			track.pause();
	}

	static void audioPlay(byte[] data, int size) {
		if (track != null)
			track.write(data, 0, size);
	}
}
